package com.gp.dwt.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gp.dwt.base.JavaMailTool;
import com.gp.dwt.base.ResultCode;
import com.gp.dwt.base.ValidateCode;
import com.gp.dwt.dto.UserLoginDto;
import com.gp.dwt.dto.UserRegisterDto;
import com.gp.dwt.mapper.UserMapper;
import com.gp.dwt.service.UserService;
import com.gp.dwt.base.Result;
import com.gp.dwt.utils.JwtUtil;
import com.gp.dwt.utils.SmsCodeGenerationUtil;
import com.gp.dwt.utils.SnowFlakeUtil;
import com.gp.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @author 小杜
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SmsCodeGenerationUtil smsCodeGenerationUtil;

    @Autowired
    private JavaMailTool javaMailTool;
    @Override
    public Result userRegister(HttpSession session, UserRegisterDto userRegisterDto) {
        //首先判断用户名是否存在.
        QueryWrapper<User> userNameQueryWrapper=new QueryWrapper<>();
        QueryWrapper<User> phoneQueryWrapper=new QueryWrapper<>();
        userNameQueryWrapper.eq("username",userRegisterDto.getUserName());
        phoneQueryWrapper.eq("email",userRegisterDto.getEmail());
        User user=userMapper.selectOne(userNameQueryWrapper);
        if (user!=null){
            return Result.responseResult(ResultCode.USER_NAME_REPEAT);
        }
        user=userMapper.selectOne(phoneQueryWrapper);
        if (user!=null){
            return Result.responseResult(ResultCode.EMAIL_REPEAT);
        }
        ValidateCode smsCoed=smsCodeGenerationUtil.generate();
        System.out.println(smsCoed);
        //发邮件
        javaMailTool.sendEmail(userRegisterDto.getEmail(),smsCoed.getCode());
        session.setAttribute(userRegisterDto.getEmail(),smsCoed);
        session.setAttribute("userName",userRegisterDto.getUserName());
        session.setAttribute("password",userRegisterDto.getPassword());
        session.setAttribute("email",userRegisterDto.getEmail());
        System.out.println("保存验证码的sessionId"+session.getId());
//        return Result.responseResult(new GetValidationVo(smsCoed.getCode(),smsCoed.getExpireTime().toString()));
        return Result.responseResult();
    }

    @Override
    public Result userValidateRegister(HttpSession session,UserRegisterDto userRegisterDto) {
        ValidateCode smsCode=(ValidateCode)session.getAttribute(session.getAttribute("email").toString());
        if (smsCode==null){
            return Result.responseResult(ResultCode.NO_VALIDATION_SENT);
        }
        if (smsCode.isExpired()){
            return Result.responseResult(ResultCode.VALIDATION_EXPIRED);
        }
        if (!userRegisterDto.getCode().equals(smsCode.getCode())){
            return Result.responseResult(ResultCode.VALIDATION_WRONG);
        }
        //开始注册
        SnowFlakeUtil idWorker=new SnowFlakeUtil(0,0);
        Long userId=idWorker.nextId();
        String encodePassword=passwordEncoder.encode(session.getAttribute("password").toString());
        userMapper.insert(new User(
                userId,
                session.getAttribute("userName").toString(),
                encodePassword,
                null,
                null,
                null,
                null,
                0L,
                session.getAttribute("email").toString()
        ));
//        验证码正确，删除session
        session.removeAttribute(userRegisterDto.getEmail());
        session.removeAttribute("userName");
        session.removeAttribute("password");
        session.removeAttribute("phone");
        return Result.responseResult();
    }


    @Override
    public Result userLoginByUserName(UserLoginDto userLoginDto) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",userLoginDto.getUserName());
        User user=userMapper.selectOne(queryWrapper);
        if (user==null){
            return Result.responseResult(ResultCode.USER_IS_NOT_EXIST);
        }
        if (passwordEncoder.matches(userLoginDto.getPassword(),user.getPsd())){
            return Result.responseResult(JwtUtil.createJWT(user.getId().toString()));
        }else{
            return Result.responseResult(ResultCode.USER_IS_NOT_EXIST);
        }
    }

    @Override
    public Result userLoginByEmail(UserLoginDto userLoginDto) {
        //通过手机号获取用户
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("email",userLoginDto.getEmail());
        User user=userMapper.selectOne(queryWrapper);
        if (user==null){
            //未注册，自动注册
            //1.生成id
            SnowFlakeUtil idWorker=new SnowFlakeUtil(0,0);
            Long userId=idWorker.nextId();
            //2.生成用户名
            String userUserName= RandomUtil.randomString(10);
            //3.生成密码
            String userPassword="password";
            String encodePassword=passwordEncoder.encode(userPassword);
            userMapper.insert(new User(
                    userId,
                    userUserName,
                    encodePassword,
                    null,
                    null,
                    null,
                    null,
                    0L,
                    userLoginDto.getEmail()
            ));
            return Result.responseResult(JwtUtil.createJWT(userId.toString()));
        }else {
            return Result.responseResult(JwtUtil.createJWT(user.getId().toString()));
        }
    }

}
